package utils;

import com.hkfs.fundamental.httpclient.ClientEx;
import constant.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

/**
 * Created by GuoXinJie on 2017-03-23.
 */
public class MsgSuDunUtils {

    private static Logger logger = LoggerFactory.getLogger(MsgSuDunUtils.class);

    public static boolean  batchSendMsg(String[] phones,String msg){
        String smsUrl = Constants.SuDun_Send_SMS_URL;
        String status = Constants.SuDun_SMS_STATUS;
        String result ;
        StringBuilder destMobile = new StringBuilder();
        for (int i = 0; i < phones.length; i++) {
            if (i == (phones.length-1)) {
                destMobile.append(phones[i]);
            }
            else {
                destMobile.append(phones[i]+",");
            }
        }

        ClientEx client = new ClientEx();
        client.form("account", Constants.SuDun_SMS_ACCOUNT);
        client.form("pswd", Constants.SuDun_SMS_PASSWORD);
        client.form("mobile", destMobile.toString());
        client.form("needstatus", "true");
        client.form("msg", msg);
        client.form("product", Constants.SuDun_SMS_PRODUCT);

        if(status.equals("1")) {
            client.post(smsUrl);
            result = client.getData();
        }else {
            result = "短信接口已关闭,0,如果有需要请开启短信接口";
        }

        boolean code =  isSmsSendSuccess(result);

        return code;
    }

    private static boolean isSmsSendSuccess(String result) {

        if (result != null) {
            result = result.replace("\n", ",");
            String[] array = result.split(",");
            if (array.length >= 3) {
                if (array[1].equals("0")) {
                    logger.info("发送短信成功:{}", result);
                    return true;
                }
            }
        }
        logger.error("发送短信失败，错误代码:{}", result);
        return false;
    }

    public static void main(String[] args) {
        String s = "20170323144448,0,2060323144448681500,";
        System.out.println(Arrays.toString(s.split(",")));
    }
}


